<template>
    <div class="page-content">
        <h3>{{ props.tableLayout === '2' ? '关键词回复列表' : props.tableLayout === '3' ? '关注回复列表' : '默认回复列表' }}</h3>
        <el-row>
            <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
                <el-button @click="showDialog('add')" v-ripple>新增规则</el-button>
            </el-col>
        </el-row>

        <art-table :data="tableData" :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize"
            :total="pageTotal" @current-change="currentChange" @size-change="sizeChange">
            <template #default>
                <el-table-column label="排序" prop="sort" align="center" width="80" />
                <el-table-column label="规则名称" prop="name" align="center" />
                <el-table-column label="关键词" prop="matchValue" align="center" v-if="props.tableLayout === '2'" />
                <el-table-column label="匹配方式" prop="isExactMatch" align="center" #default="scope"
                    v-if="props.tableLayout === '2'">
                    {{ scope.row.isExactMatch === 1 ? '全匹配' : '模糊匹配' }}
                </el-table-column>
                <el-table-column label="回复类型" prop="type" align="center" #default="scope">
                    {{ scope.row.type === 1 ? '关注回复' : scope.row.type === 2 ? '关键词回复' : '默认回复' }}
                </el-table-column>
                <el-table-column label="回复内容" prop="replyContent" align="center" v-if="props.tableLayout !== '2'" />
                <el-table-column label="状态" prop="status" #default="scope" align="center">
                    <el-switch v-model="scope.row.status" :inactive-value="0" :active-value="1"
                        @change="EditStatus(scope.row.id, scope.row.status)" />
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="150px" align="center">
                    <template #default="scope">
                        <button-table type="edit" @click="buttonMoreClick(scope.row)" />
                        <button-table type="delete" @click="deleteRole(scope.row.id)" />
                    </template>
                </el-table-column>
            </template>
        </art-table>

        <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增回复' : '编辑回复'" width="23%"
            :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="排序：" prop="sort">
                    <el-input v-model="form.sort" :rows="3" />
                </el-form-item>
                <el-form-item label="规则名称：" prop="name">
                    <el-input v-model="form.name" placeholder="请输入规则名称" />
                </el-form-item>
                <el-form-item label="关键词：" prop="matchValue" v-if="props.tableLayout === '2'">
                    <el-input v-model="form.matchValue" placeholder="请输入关键词" />
                </el-form-item>
                <el-form-item label="匹配方式：" prop="isExactMatch" v-if="props.tableLayout === '2'">
                    <el-radio-group v-model="form.isExactMatch">
                        <el-radio value="1" checked>全匹配</el-radio>
                        <el-radio value="0" checked>模糊匹配</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="回复类型：" prop="replyType">
                    <el-radio-group v-model="form.replyType">
                        <el-radio value="text" checked>文本</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="回复内容" prop="replyContent">
                    <el-input v-model="form.replyContent" type="textarea" :rows="6" placeholder="请输入回复内容" />
                </el-form-item>
                <el-form-item label="启用状态" prop="status">
                    <el-switch v-model="form.status" :inactive-value="0" :active-value="1" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getAutoReplyPage, addAutoReply, delAutoReply, editAutoReply } from '@/api/marketing'

const dialogVisible = ref(false)
const fixedTime = ref<[Date, Date] | []>([])
const formRef = ref<FormInstance>()

const props = defineProps({
    tableLayout: {
        type: String
    }
})


const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入规则名称', trigger: 'blur' },
    ],
    replyType: [{ required: true, message: '请选择回复类型', trigger: 'change' }],
    replyContent: [{ required: true, message: '请输入回复内容', trigger: 'blur' }],
    matchValue: [{ required: true, message: '请输入关键词', trigger: 'blur' }],
    isExactMatch: [{ required: true, message: '请选择匹配方式', trigger: 'change' }],
})

const form = reactive({
    id: '',
    name: '',
    type: 0,
    sort: 1,
    status: 1,
    replyType: 'text',
    replyContent: '',
    matchValue: '',
    isExactMatch: '1'
})
const searchForm = reactive({
    queryCondition: ''
})

const tableData = ref([])

const dialogType = ref('add')

const showDialog = (type: string, row?: any) => {
    dialogVisible.value = true
    dialogType.value = type


    if (type === 'edit' && row) {
        form.id = row.id
        console.log(form.id, "form.id=");
        form.name = row.name
        form.type = row.type
        form.sort = row.sort
        form.status = row.status
        form.replyType = row.replyType
        form.matchValue = row.matchValue
        form.isExactMatch = String(row.isExactMatch)
        form.replyContent = row.replyContent
    } else {
        form.id = ''
        form.name = ''
        form.type = 0
        form.sort = 1
        form.status = 1
        form.matchValue = ''
        form.isExactMatch = '1'
        form.replyContent = ''
    }
}

const buttonMoreClick = (row: any) => {
    showDialog('edit', row)
}


const deleteRole = (id: number) => {
    ElMessageBox.confirm('确定删除该优惠券吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
    }).then(async () => {
        const res = await delAutoReply(id)
        if (res.code === '00000') {
            ElMessage.success('删除成功')
            getData()
        }

    })
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid) => {
        if (valid) {
            const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
            form.type = props.tableLayout === '2' ? 2 : props.tableLayout === '3' ? 1 : 3
            const params: any = filterEmptyValues(form)
            if (form.id) {
                const res = await editAutoReply(form.id, params)
                if (res.code === '00000') {
                    ElMessage.success(message)
                    dialogVisible.value = false
                    getData()
                }
            } else {
                const res = await addAutoReply(params)
                if (res.code === '00000') {
                    ElMessage.success(message)
                    dialogVisible.value = false
                    getData()
                }
            }
        }
    })
}

const formatDate = (date: string) => {
    return new Date(date)
        .toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        })
        .replace(/\//g, '-')
}

const currentChange = (val: number) => {
    pageNum.value = val
    getData()
}

const sizeChange = (val: number) => {
    pageSize.value = val
    pageNum.value = 1
    getData()
}

const tableLoading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)

const filterEmptyValues = (obj: any) => {
    const result: any = {}
    for (const key in obj) {
        if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
            result[key] = obj[key]
        }
    }
    return result
}

const getData = async () => {
    tableLoading.value = true
    try {
        const params = filterEmptyValues(searchForm)
        const res = await getAutoReplyPage({
            pageSize: pageSize.value,
            pageNum: pageNum.value,
            type: props.tableLayout === '2' ? 2 : props.tableLayout === '3' ? 1 : 3
        })
        if (res.code === '00000') {
            tableData.value = res.data.list
            pageTotal.value = res.data.total
        }
    } catch { } finally {
        tableLoading.value = false
    }

}


const EditStatus = async (id: string, status: number) => {
    try {
        const res = await editAutoReply(id, {
            status
        })
        if (res.code === '00000') {
            ElMessage.success('修改成功')
        }
    } catch (e) {
    } finally {
        await getData()
    }
}
onMounted(() => {
    getData()
})
</script>

<style lang="scss" scoped>
.page-content {
    .svg-icon {
        width: 1.8em;
        height: 1.8em;
        overflow: hidden;
        vertical-align: -8px;
        fill: currentcolor;
    }

    h3 {
        font-weight: bold;
        margin-bottom: 20px;
    }
}

:deep(.el-row) {
    justify-content: space-between;
}
</style>